package com.tencreat.api.controller;

import cn.hutool.json.JSONUtil;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.entity.ImSetting;
import com.tencreat.common.entity.ImSettingBackground;
import com.tencreat.common.entity.ImSettingBackgroundBrief;
import com.tencreat.common.entity.ImUser;
import com.tencreat.common.service.ImSettingService;
import com.tencreat.common.service.ImUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * 管理后台接口
 */
@RestController
@RequestMapping("/admin")
public class ImAdminController {

    @Autowired
    ImSettingService imSettingService;
    @Autowired
    ImUserService imUserService;

    /**
     * 后台配置信息
     * @return
     */
    @PostMapping("/setting/background/info")
    public HttpResult<ImSettingBackground> backgroundInfo(){
        ImSetting one = imSettingService.lambdaQuery().eq(ImSetting::getName, ImSettingBackground.KEY).one();
        ImSettingBackground bean = JSONUtil.parse(one.getValue()).toBean(ImSettingBackground.class);
        return HttpResult.ok(bean);
    }

    /**
     * 更新配置信息
     * @param setting
     * @return
     */
    @PostMapping("/setting/background/update")
    @Transactional
    public HttpResult<Boolean> backgroundUpdate(@RequestBody ImSettingBackground setting){
        boolean update = imUserService.lambdaUpdate().eq(ImUser::getId, 1L)
                .set(ImUser::getPassword, setting.getPassword())
                .set(ImUser::getUsername, setting.getUsername())
                .set(ImUser::getNickname, setting.getNickname())
                .set(ImUser::getAvatar, setting.getAdminAvatar())
                .update();


        imSettingService.updateBackGroundSetting(setting);
        return HttpResult.ok(update);
    }
}
